import React, { useState, useEffect, useRef } from 'react';
import { Card, Typography, Tag, Spin, Button, Space, Descriptions } from 'antd';
import { ReloadOutlined } from '@ant-design/icons';
import { scriptApi } from '@/services/api';
import type { ScriptExecution } from '@/types';
import { io, Socket } from 'socket.io-client';

const { Text, Paragraph } = Typography;

interface ExecutionResultProps {
  execution: ScriptExecution;
}

const ExecutionResult: React.FC<ExecutionResultProps> = ({ execution: initialExecution }) => {
  console.log('[DEBUG] ExecutionResult component rendered with execution:', initialExecution);
  
  // 确保使用正确的初始值，如果initialExecution有data字段，提取它
  const correctInitialExecution = initialExecution.data || initialExecution;
  console.log('[DEBUG] Correct initial execution:', correctInitialExecution);
  
  const [execution, setExecution] = useState<ScriptExecution>(correctInitialExecution);
  
  console.log('[DEBUG] ExecutionResult state execution:', execution);
  
  // 当props中的execution变化时，更新state
  useEffect(() => {
    const newExecution = initialExecution.data || initialExecution;
    console.log('[DEBUG] Props execution changed, updating state from:', execution.id, 'to:', newExecution.id);
    setExecution(newExecution);
  }, [initialExecution]);
  const [loading, setLoading] = useState(false);
  const [realtimeOutput, setRealtimeOutput] = useState<string>('');
  const [realtimeError, setRealtimeError] = useState<string>('');
  const socketRef = useRef<Socket | null>(null);
  const outputRef = useRef<HTMLPreElement>(null);

  const refreshExecution = async () => {
    console.log('[DEBUG] refreshExecution called with execution.id:', execution.id);
    setLoading(true);
    try {
      const response = await scriptApi.getExecutionById(execution.id);
      console.log('[DEBUG] refreshExecution API response:', response);
      const updatedExecution = response.data;
      console.log('[DEBUG] refreshExecution extracted execution:', updatedExecution);
      setExecution(updatedExecution);
    } catch (error) {
      console.error('刷新执行结果失败:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    console.log('[DEBUG] WebSocket useEffect triggered with execution.id:', execution.id);
    console.log('[DEBUG] WebSocket useEffect execution object:', execution);
    
    if (!execution || !execution.id) {
      console.error('[DEBUG] execution.id is invalid:', execution?.id);
      return;
    }
    
    // 重置实时输出状态
    setRealtimeOutput('');
    setRealtimeError('');
    
    console.log('[DEBUG] Setting up WebSocket connection for execution:', execution.id);
    
    // 建立WebSocket连接
    const token = localStorage.getItem('token');
    socketRef.current = io('/scripts', {
      auth: {
        token,
      },
      transports: ['websocket'],
    });

    const socket = socketRef.current;

    // 订阅执行结果
    console.log('[DEBUG] Subscribing to execution:', execution.id);
    socket.emit('subscribe-execution', { executionId: execution.id });

    // 监听实时输出
    socket.on('execution-output', (data: { executionId: number; data: string; timestamp: string }) => {
      console.log('[DEBUG] Received execution-output:', data);
      console.log('[DEBUG] Comparing with execution.id:', execution.id);
      if (data.executionId === execution.id) {
        console.log('[DEBUG] Output matches current execution, updating UI');
        setRealtimeOutput(prev => prev + data.data);
        // 自动滚动到底部
        setTimeout(() => {
          if (outputRef.current) {
            outputRef.current.scrollTop = outputRef.current.scrollHeight;
          }
        }, 100);
      } else {
        console.log('[DEBUG] Output for different execution, ignoring');
      }
    });

    // 监听错误输出
    socket.on('execution-error', (data: { executionId: number; error: string; timestamp: string }) => {
      if (data.executionId === execution.id) {
        setRealtimeError(prev => prev + data.error);
      }
    });

    // 监听状态更新
    socket.on('execution-status', (data: { executionId: number; status: string; exitCode?: number; timestamp: string }) => {
      console.log('[DEBUG] Received execution-status:', data);
      if (data.executionId === execution.id) {
        console.log('[DEBUG] Status update matches current execution, updating state');
        setExecution(prev => {
          console.log('[DEBUG] Previous execution state in status update:', prev);
          // 确保prev是execution对象而不是API响应
          const currentExecution = prev.data || prev;
          const updated = {
            ...currentExecution,
            status: data.status as any,
            exitCode: data.exitCode,
            endTime: data.status !== 'running' ? data.timestamp : currentExecution.endTime,
          };
          console.log('[DEBUG] Updated execution state:', updated);
          return updated;
        });
      }
    });

    // 连接确认
    socket.on('subscription-confirmed', (data: { executionId: number }) => {
      console.log('[DEBUG] Subscription confirmed for execution:', data.executionId);
    });
    
    // 订阅错误
    socket.on('subscription-error', (data: { error: string; executionId: any }) => {
      console.error('[DEBUG] Subscription error:', data);
    });

    return () => {
      console.log('[DEBUG] Cleaning up WebSocket connection for execution:', execution.id);
      socket.emit('unsubscribe-execution', { executionId: execution.id });
      socket.disconnect();
    };
  }, [execution.id]);

  const getStatusTag = (status: string) => {
    const statusMap = {
      running: { color: 'processing', text: '运行中' },
      completed: { color: 'success', text: '完成' },
      failed: { color: 'error', text: '失败' },
      cancelled: { color: 'warning', text: '已取消' },
    };
    const config = statusMap[status] || { color: 'default', text: status };
    return <Tag color={config.color}>{config.text}</Tag>;
  };

  const formatDuration = (startTime: string, endTime?: string) => {
    const start = new Date(startTime);
    const end = endTime ? new Date(endTime) : new Date();
    const duration = Math.round((end.getTime() - start.getTime()) / 1000);
    
    if (duration < 60) {
      return `${duration}秒`;
    } else if (duration < 3600) {
      return `${Math.floor(duration / 60)}分${duration % 60}秒`;
    } else {
      const hours = Math.floor(duration / 3600);
      const minutes = Math.floor((duration % 3600) / 60);
      const seconds = duration % 60;
      return `${hours}时${minutes}分${seconds}秒`;
    }
  };

  return (
    <Spin spinning={loading}>
      <div>
        <div style={{ marginBottom: 8, padding: 8, backgroundColor: '#f0f0f0', fontSize: '12px' }}>
          DEBUG: Execution ID: {execution.id} | Status: {execution.status} | UseEffect should have run
        </div>
        <Card size="small" style={{ marginBottom: 16 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <div>
              <Text strong>执行状态: </Text>
              {getStatusTag(execution.status)}
            </div>
            <Button
              icon={<ReloadOutlined />}
              onClick={refreshExecution}
              size="small"
            >
              刷新
            </Button>
          </div>
        </Card>

        <Card title="执行信息" size="small" style={{ marginBottom: 16 }}>
          <Descriptions column={2} size="small">
            <Descriptions.Item label="执行ID">{execution.id}</Descriptions.Item>
            <Descriptions.Item label="脚本ID">{execution.scriptId}</Descriptions.Item>
            <Descriptions.Item label="开始时间">
              {new Date(execution.startTime).toLocaleString()}
            </Descriptions.Item>
            <Descriptions.Item label="结束时间">
              {execution.endTime ? new Date(execution.endTime).toLocaleString() : '-'}
            </Descriptions.Item>
            <Descriptions.Item label="执行时长">
              {formatDuration(execution.startTime, execution.endTime)}
            </Descriptions.Item>
            <Descriptions.Item label="退出码">
              {execution.exitCode !== undefined ? execution.exitCode : '-'}
            </Descriptions.Item>
          </Descriptions>
        </Card>

        {(execution.output || realtimeOutput) && (
          <Card title="输出结果" size="small" style={{ marginBottom: 16 }}>
            <pre
              ref={outputRef}
              style={{
                backgroundColor: '#f5f5f5',
                padding: 16,
                borderRadius: 4,
                overflow: 'auto',
                maxHeight: 300,
                fontFamily: 'Monaco, Consolas, "Courier New", monospace',
                fontSize: 14,
                lineHeight: 1.5,
                margin: 0,
                whiteSpace: 'pre-wrap',
              }}
            >
              {execution.status === 'running' ? realtimeOutput : (execution.output || realtimeOutput)}
            </pre>
          </Card>
        )}

        {(execution.error || realtimeError) && (
          <Card title="错误信息" size="small">
            <pre
              style={{
                backgroundColor: '#fff2f0',
                padding: 16,
                borderRadius: 4,
                overflow: 'auto',
                maxHeight: 300,
                fontFamily: 'Monaco, Consolas, "Courier New", monospace',
                fontSize: 14,
                lineHeight: 1.5,
                margin: 0,
                whiteSpace: 'pre-wrap',
                color: '#cf1322',
              }}
            >
              {execution.status === 'running' ? realtimeError : (execution.error || realtimeError)}
            </pre>
          </Card>
        )}

        {execution.status === 'running' && !realtimeOutput && !realtimeError && (
          <Card>
            <div style={{ textAlign: 'center', padding: 32 }}>
              <Spin size="large" />
              <div style={{ marginTop: 16 }}>
                <Text type="secondary">脚本正在执行中，请稍候...</Text>
              </div>
            </div>
          </Card>
        )}
      </div>
    </Spin>
  );
};

export default ExecutionResult;